package com.itheima.controller.backend.security;

import com.itheima.pojo.Permission;
import com.itheima.pojo.Role;
import com.itheima.pojo.User;
import com.itheima.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@Service
public class SpringSecurityUserService implements UserDetailsService {
    //查找服务，实现查询数据库
    @Autowired
    private UserService userService;

    //根据用户名查询数据库中用户信息
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 1 通过用户名查询用户,并通过多表查询获取用户对应的角色和权限
        User user = userService.findUserByUsername(username);
        if (user == null){
            // 没有该用户
            throw new UsernameNotFoundException("用户名不存在");
        }
        // 创建用于存储用户角色权限的list
        List<GrantedAuthority> list = new ArrayList<>();
        // 从查询出来的用户中获取角色
        Set<Role> roles = user.getRoles();
        for (Role role : roles) {
            // 将角色转为SimpleGrantedAuthority对象添加到权限列表
            list.add(new SimpleGrantedAuthority(role.getKeyword()));
            // 从角色中获取`权限
            Set<Permission> permissions = role.getPermissions();
            for (Permission permission : permissions) {
                // 将权限转化为SimpleGrantedAuthority对象添加到权限列表
                list.add(new SimpleGrantedAuthority(permission.getKeyword()));
            }
        }
        // 使用spring security提供的User类（实现了UserDetails接口）构建并返回UserDatails对象，传入用户名，密码，权限列表，spring security会自动校验密码
        org.springframework.security.core.userdetails.User securityUser = new org.springframework.security.core.userdetails.User(username, user.getPassword(), list);
        return securityUser;
    }
}
